const md5 = require('md5');
const { loginService, updateService } = require('../services/adminService');
const AppError = require('../utils/AppError');
const { pick, to, sendResult } = require('../utils/tools');
const { createToken } = require('../middleware/auth');

class AdminController {
	async login(req, res, next) {
		const schema = req.joi
			.object({
				loginId: req.joi.string().max(15).required(),
				loginPwd: req.joi.string().min(6).required(),
				remember: req.joi.number()
			})
			.unknown(true); // 允许请求中包含未定义的字段
		const { error: failed } = schema.validate(req.body);
		if (failed) return next(new AppError(failed, 400));

		// 登录
		req.body.loginPwd = md5(req.body.loginPwd);
		const body = pick(req.body, 'loginId', 'loginPwd');
		const [error, result] = await to(loginService(body));
		if (error) return next(new AppError(error, 401));

		// 创建token，传入过期时间
		const { accessToken, refreshToken, expiresIn } = await createToken({ ...result, remember: req.body.remember || 1 }, next);
		result.token = accessToken;
		result.refreshToken = refreshToken;
		result.expiresIn = expiresIn;
		result.tokenType = 'Bearer';
		res.cookie('token', accessToken);
		res.setHeader('authorization', accessToken);

		// 响应
		res.send(sendResult(result, '登录成功'));
	}

	// 管理员更新自己信息
	async update(req, res, next) {
		const schema = req.joi.object({
			name: req.joi.string().required(),
			loginPwd: req.joi.string().min(6).required(),
			oldLoginPwd: req.joi.string().min(6).required()
		});
		const { error: failed } = schema.validate(req.body);
		if (failed) return next(new AppError(failed, 400));

		req.body.loginPwd = md5(req.body.loginPwd);
		req.body.oldLoginPwd = md5(req.body.oldLoginPwd);
		req.body.loginId = req.auth.loginId;
		// 校验旧密码是否正确
		const [error, result] = await to(
			loginService({
				loginId: req.body.loginId,
				loginPwd: req.body.oldLoginPwd
			})
		);
		if (error) return next(new AppError('旧密码错误', 401));

		// 更新密码
		const body = pick(req.body, 'loginId', 'loginPwd', 'name');
		const [uperror, upresult] = await to(updateService(body, req.auth.id));
		if (uperror) return next(new AppError(uperror, 401));

		res.send(
			sendResult({
				id: req.auth.id,
				name: req.body.name,
				loginId: req.body.loginId
			})
		);
	}

	// 超级管理员更新密码

	// 获取token中的用户信息
	async whoami(req, res, next) {
		res.send(sendResult(req.auth));
	}
}

module.exports = new AdminController();
